<template>
  <el-dialog
    v-model="dialogVisible"
    destroy-on-close
    fullscreen
    :title="dialogTitle"
    @close="closeDialog"
  >
    <el-form
      :inline="true"
      label-position="left"
      label-width="120px"
      :model="formData"
    >
      <el-form-item label="模板编码">
        <el-input
          v-model.trim="formData.printTemplateCode"
          clearable
          :disabled="opt !== 'add'"
          placeholder="请输入编码"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="模板名称">
        <el-input
          v-model.trim="formData.printTemplateName"
          clearable
          placeholder="请输入名称"
          style="width: 200px"
        />
      </el-form-item>
    </el-form>
    <iframe
      v-if="dialogVisible"
      ref="hiIframeRef"
      :src="`/hiprint/index.html?a=${randomUrl}`"
      style="
        width: 100%;
        height: calc(100vh - 180px);
        border: 1px solid #e0e0e0;
      "
      @load="iframeLoaded"
    ></iframe>
  </el-dialog>
</template>
<script setup>
  import { addPrintTemp, editPrintTemp } from '@/api/print/index.js'
  import { localStorageConfig } from '@/config/localstorage.config'
  const $baseMessage = inject('$baseMessage')
  const dialogVisible = ref(false),
    dialogTitle = ref('标签设计'),
    opt = ref('add'),
    formData = reactive({
      pkPrintTemplate: '',
      printTemplateCode: '',
      printTemplateName: '',
      printTemplateBody: '',
    }),
    hiIframeRef = ref(),
    hasOnload = ref(false),
    randomUrl = Math.floor(Math.random() * 100),
    pkCorp = localStorage.getItem(localStorageConfig.__pkCorp)

  const closeDialog = () => {
    dialogVisible.value = false
    hasOnload.value = false
    console.log('closeDialog')
    window.removeEventListener('message', handleMessage)
  }

  const _emits = defineEmits(['add-success'])

  let stepIndex = 0
  const toSendMessage = (body, opt) => {
    if (stepIndex >= 10) return
    if (
      hiIframeRef.value &&
      hiIframeRef.value.contentWindow &&
      hasOnload.value
    ) {
      setTimeout(() => {
        hiIframeRef.value.contentWindow.postMessage(
          { ...body, type: 'hiprint', opt },
          '*'
        )
      }, 0)
    } else {
      setTimeout(() => {
        stepIndex++
        toSendMessage(body, opt)
      }, 200)
    }
  }

  const handleMessage = function (event) {
    if (event.data) {
      if (event.data.type === 'onLoad') {
        console.log('onLoad')
        hasOnload.value = true
        return
      }
      if (event.data.type !== 'hiprint') {
        return
      }
      delete event.data.type
      delete event.data.opt

      const templateStr = JSON.stringify(event.data)
      if (
        !templateStr ||
        !formData.printTemplateCode ||
        !formData.printTemplateName
      ) {
        $baseMessage('请完善数据', 'error')
      } else {
        saveData(templateStr, opt.value).then((res) => {
          if (res.code === 2000) {
            dialogVisible.value = false
            _emits('add-success')
          }
        })
      }
    }
  }

  const messageEventListener = () => {
    window.addEventListener('message', handleMessage)
  }
  const saveData = (templateStr, opt) => {
    const params = {
      ...formData,
      printTemplateBody: templateStr,
      pkCorp,
    }
    switch (opt) {
      case 'add':
        return addPrintTemp(params)
      case 'edit':
        return editPrintTemp(params)
    }
  }

  defineExpose({
    handleOpen: () => {
      dialogVisible.value = true
      opt.value = 'add'
      formData.printTemplateCode = ''
      formData.printTemplateName = ''
      nextTick(() => {
        toSendMessage({}, 'add')
      })
      messageEventListener()
    },
    handleEditOpen: (rowItem) => {
      dialogVisible.value = true
      opt.value = 'edit'
      const {
        printTemplateBody,
        printTemplateCode,
        printTemplateName,
        pkPrintTemplate,
      } = rowItem
      formData.printTemplateCode = printTemplateCode || ''
      formData.printTemplateName = printTemplateName || ''
      formData.pkPrintTemplate = pkPrintTemplate || ''
      let body = null
      try {
        body = JSON.parse(printTemplateBody) || {}
        toSendMessage(body, 'edit')
      } catch (error) {
        body = {}
        toSendMessage(body, 'add')
      }
      messageEventListener()
    },
  })
</script>
